# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:2025/5/17
desc: 
sample: 
"""
import json

from django_celery_beat.models import CrontabSchedule
from dvadmin_celery.views.task import CronSlpit, CeleryCrontabScheduleSerializer, PeriodicTasksSerializer
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from apitest.models import EnvInfo, ProjectInfo, ModuleInfo, TestApiInfo, TestApiResult, TestCase
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.string_util import is_json


class EnvInfoSerializer(CustomModelSerializer):

    def validate_paramsbody(self,value):
        if value is not None or value != '':
            if is_json(value)==False:
                raise serializers.ValidationError("请输入正确的json格式")
        return value

    class Meta:
        model = EnvInfo
        fields = '__all__'

class ProjectInfoSerializer(CustomModelSerializer):
    class Meta:
        model = ProjectInfo
        fields = '__all__'

class ModuleInfoSerializer(CustomModelSerializer):
    class Meta:
        model = ModuleInfo
        fields = '__all__'


class TestApiInfoSerializer(CustomModelSerializer):

    def validate(self, attr):
        header = attr.get('headers')
        if header is not None and header != '':
            if is_json(header) == False:
                raise ValidationError({'头部信息问题': '不是json格式'})
        jsonbody = attr.get('jsonbody')
        if jsonbody is not None and jsonbody != '':
            if is_json(jsonbody) == False:
                raise ValidationError({'json参数问题': '不是json格式'})
        return attr

    class Meta:
        model = TestApiInfo
        fields = '__all__'

class ExportTestApiInfoSerializer(CustomModelSerializer):
    method_name = serializers.CharField(source="get_method_display")
    project_name  = serializers.CharField(source="project_belong.project_name", default="")
    module_name = serializers.CharField(source="module_belong.module_name", default="")
    headers = serializers.SerializerMethodField(read_only=True)

    def get_headers(self, instance):
        if instance.headers == '{}':
            return ''

    class Meta:
        model = TestApiInfo
        fields = '__all__'


class TestApiInfoImportSerializer(CustomModelSerializer):

    def validate(self, attr):
        project_belong = attr.get('project_belong')
        module_belong = attr.get('module_belong')
        if project_belong is not None and module_belong is not None:
            if project_belong.id != module_belong.project_belong_id:
                raise ValidationError({'项目所属问题': '请选择正确的项目'})
        headers = attr.get('headers')
        if headers is not None and headers != '':
            if is_json(headers) == False:
                raise ValidationError({'头部信息问题': '不是json格式'})
        jsonbody = attr.get('jsonbody')
        if jsonbody is not None and jsonbody != '':
            if is_json(jsonbody) == False:
                raise ValidationError({'json参数问题': '不是json格式'})
        return attr

    def save(self, **kwargs):
        name = self.initial_data.get('name')
        #修改
        if TestApiInfo.objects.filter(name=name).exists():
            TestApiInfo.objects.filter(name=name).update(**self.initial_data)
        else:
          return super().save(**kwargs)

    class Meta:
        model = TestApiInfo
        fields = '__all__'







class TestApiResultSerializer(CustomModelSerializer):
    class Meta:
        model = TestApiResult
        fields = '__all__'


class TestCaseSerializer(CustomModelSerializer):
    cron=serializers.SerializerMethodField(read_only=True)

    def get_cron(self, instance):
        # if instance.cron is None or instance.cron == '':
        #     return '未设置时间'
        if instance.task_belong is None:
            return '未设置时间'
        else: return instance.task_belong.crontab.__str__()

    # def save(self, **kwargs):
    #     #case表
    #     case= super().save(**kwargs)
    #     # 修改用例时，如果定时任务不为空，则修改定时任务
    #     cron = self.initial_data.get('cron')
    #     if cron is not None and cron != '':
    #         cron_data = CronSlpit(cron)
    #         # 添加crontab
    #         serializer = CeleryCrontabScheduleSerializer(data=cron_data)
    #         serializer.is_valid(raise_exception=True)
    #         print(cron_data)
    #         #serializer.save()
    #         schedule, created = CrontabSchedule.objects.get_or_create(**cron_data)  # 手动创建crontab，避免重复创建
    #         #PeriodicTasks
    #         body_data={}
    #         print(schedule.id)
    #         body_data['name'] = case.case_name
    #         body_data['crontab'] = schedule.id
    #         body_data['enabled'] = True
    #         body_data['task'] = 'apitest.tasks.task__api'
    #         env = self.initial_data.get('env')
    #         env_id =env.get('id')
    #         body_data['kwargs'] = json.dumps({'case_id': case.id,'env_id':env_id})
    #         serializer= PeriodicTasksSerializer(data=body_data)
    #         serializer.is_valid(raise_exception=True)
    #         serializer.save()
    #     return case

    class Meta:
        model = TestCase
        fields = '__all__'


